package com.ruoyi.boat.aop;

import com.ruoyi.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Aspect
@Slf4j
@Component
public class AvoidDuplicationAspect {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Around("@annotation(AvoidDuplicate)")
    public Object avoid(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取注解参数
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AvoidDuplicate annotation = method.getAnnotation(AvoidDuplicate.class);
        int seconds = annotation.seconds();
        String message = annotation.message();

        // 获取函数参数
        Object[] args = joinPoint.getArgs();
        String name = args[0].toString();

        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("order:" + name, String.valueOf(System.currentTimeMillis()), seconds, TimeUnit.SECONDS);
        Object result;
        if (Boolean.TRUE.equals(aBoolean)) {
            result = joinPoint.proceed();
        } else {
            result = AjaxResult.error(message);
        }
        return result;
    }

}
